package org.jeecg.modules.tencent_esign.tencent_flowsfile.service.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ess.v20201111.models.DescribeFlowInfoRequest;
import com.tencentcloudapi.essbasic.v20210526.EssbasicClient;
import com.tencentcloudapi.essbasic.v20210526.models.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.health_records.files_upload.FileUploadUtil;
import org.jeecg.modules.tencent_esign.tencent_flowsfile.entity.TencentFlowsFile;
import org.jeecg.modules.tencent_esign.tencent_flowsfile.mapper.TencentFlowsFileMapper;
import org.jeecg.modules.tencent_esign.tencent_flowsfile.service.ITencentFlowsFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 电子签合同下载路径存储表
 * @Author: jeecg-boot
 * @Date:   2025-08-13
 * @Version: V1.0
 */
@Service
public class TencentFlowsFileServiceImpl extends ServiceImpl<TencentFlowsFileMapper, TencentFlowsFile> implements ITencentFlowsFileService {
    @Value("${tencent.esign.secret-key}")
    private String secretKey;
    @Value("${tencent.esign.secret-id}")
    private String secretId;

    @Value("${tencent.esign.endpoint}")
    private String endpoint;
    @Value("${tencent.esign.region}")
    private String region;
    @Value("${tencent.esign.sdk-app-id}")
    private String appId;

    @Value("${tencent.esign.download.base-path}")
    private String savePath;
    @Value("${tencent.esign.download.static-path}")
    private String staticPath;
    @Value("${tencent.esign.download.access-path}")
    private String accessPath;
    @Autowired
    private TencentFlowsFileMapper tencentFlowsFileMapper;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    // 初始化客户端
    public EssbasicClient getInitClient() {

        Credential cred = new Credential(secretId, secretKey);

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint); // 接口域名 第三方应用集成 联调环境

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化一个client
        EssbasicClient client = new EssbasicClient(cred, region, clientProfile);
        return client;

    }

    /**
     * 下载已签署完成的合同
     * @param flowId 合同流程ID
     * @param contractName 合同名称
     * @return 操作结果
     */
    @Override
    public Result<String> downloadSignedContract(String flowId, String contractName,String openId, String proxyOrganizationOpenId) {
        try {
            // 1.初始化客户端
            // 实例化一个client
            EssbasicClient client = getInitClient();
            // 2. 创建下载请求
            DescribeFlowInfoRequest req = new DescribeFlowInfoRequest();
            req.setFlowIds(new String[]{flowId});

            // 3. 获取合同信息
         /*   DescribeFlowInfoResponse resp = client.D;
            if (resp.getFlowDetailInfos() == null || resp.getFlowDetailInfos().length == 0) {
                return Result.error("未找到对应的合同信息");
            }

            FlowDetailInfo flowInfo = resp.getFlowDetailInfos()[0];
            if (!"3".equals(flowInfo.getFlowStatus())) {
                return Result.error("合同尚未签署完成，当前状态: " + flowInfo.getFlowStatus());
            }
*/
            // 4. 创建下载URL请求
            DescribeResourceUrlsByFlowsRequest urlReq = new DescribeResourceUrlsByFlowsRequest();
            urlReq.setFlowIds(new String[]{flowId});
            // 设置操作人信息
            UserInfo operator = new UserInfo();
            operator.setOpenId(openId);
            // 设置代理应用信息（如有）
            if (appId != null) {
                Agent agent = new Agent();
                agent.setAppId(appId);
                agent.setProxyOrganizationOpenId(proxyOrganizationOpenId);//给子企业起的一个代号，需要自己定义
                agent.setProxyOperator(operator); //子企业员工的个性化标识
                urlReq.setAgent(agent);
            }

            // 5. 获取下载URL
            DescribeResourceUrlsByFlowsResponse urlResp = client.DescribeResourceUrlsByFlows(urlReq);
            if (urlResp.getFlowResourceUrlInfos() == null || urlResp.getFlowResourceUrlInfos().length == 0) {
                return Result.error("未获取到合同下载URL");
            }
            FlowResourceUrlInfo fileUrlInfo = urlResp.getFlowResourceUrlInfos()[0];

            String downloadUrl = fileUrlInfo.getResourceUrlInfos()[0].getUrl();
            // 按日期生成目录
            String dateDir = sdf.format(new Date());
            String savePathNew = savePath + File.separator + dateDir + File.separator;

            // 6. 确保保存目录存在
            File saveDir = new File(savePathNew);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
            // 7. 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + ".pdf";
            String filePath = Paths.get(savePathNew, fileName).toString();

            // 8. 下载文件
            downloadPdfFromTencentESign(downloadUrl, filePath);
            // 9.构建访问URL
            String accessUrl = accessPath+ filePath.replace("\\", "/");
            // 10. 保存到数据库
            TencentFlowsFile contractFile = new TencentFlowsFile();
            contractFile.setFlowId(flowId);
            contractFile.setFlowName(contractName);
            contractFile.setFilePath(accessUrl);
            contractFile.setCreateTime(new Date());
            contractFile.setUpdateTime(new Date());
            this.save(contractFile);
            return Result.OK("合同下载成功", filePath);
        } catch (TencentCloudSDKException e) {
            log.error("腾讯电子签SDK调用失败", e);
            return Result.error("合同下载失败: " + e.getMessage());
        } catch (IOException e) {
            log.error("文件下载失败", e);
            return Result.error("文件保存失败: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 使用URLConnection下载文件到本地
     * @param fileUrl 文件URL
     * @param savePath 保存路径
     * @throws IOException
     */
    public void downloadPdfFromTencentESign(String fileUrl, String savePath) throws Exception {
        URL url = new URL(fileUrl);
        try (InputStream in = url.openStream()) {
            Files.copy(in, Paths.get(savePath), StandardCopyOption.REPLACE_EXISTING);
        }catch (Exception e) {
            log.error("下载出错！", e);
            throw new RuntimeException(e);
        }
    }


    /**按flowId查询**/
    @Override
    public List<TencentFlowsFile> queryByFlowId(String flowId) {
        return tencentFlowsFileMapper.queryByFlowId(flowId);

    }

}
